import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { StartGameMessageData } from "../types/MessageData";
import { herosTable } from "../../../database/heros-table";
import { deepClone } from "../../../utils/conversion";
import { cardsTable } from "../../../database/cards-table";
import { shuffle } from "../utils/shuffle";

export const startGameHandler = ({ user, payload }: { client: WebSocket; user: User; payload: StartGameMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	if (room) {
		room.players.forEach((player) => {
			player.heros.length = 0;
			player.hiddenHeroIds.length = 0;
			player.healthLimit = 0;
			player.health = 0;
			player.skills.length = 0;
			player.flipped = false;
			player.tied = false;
			player.handCards.length = 0;
			player.materielCards.length = 0;
			player.delayedCards.length = 0;
			player.buckleCards.length = 0;
			player.marks.length = 0;
			player.dead = false;
		});
		room.drawCards.length = 0;
		room.discardCards.length = 0;
		room.heros.length = 0;
		room.heros.push(...shuffle(deepClone(herosTable.heros)));
		room.drawCards.push(...shuffle(deepClone(cardsTable.cards)));
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "startedGame", payload: { roomId: room.roomId } })));
		const log = { userId: user.userId, username: user.username, log: "开始了游戏。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
